//
//  TimeDownBtn.m
//  HuaXin
//
//  Created by 江伟 on 2018/11/12.
//

#import "TimeDownBtn.h"
@interface TimeDownBtn()
@property (nonatomic,assign) int timeIndex;

@end

@implementation TimeDownBtn

- (void)startTimeDown {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _timeIndex = 60;
    [self setTitle:@"60s" forState:UIControlStateNormal];
    _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeDownAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    self.enabled = NO;
}

- (void)timeDownAction {
    _timeIndex -= 1;
    if (_timeIndex == 0) {
        self.enabled = YES;
        [self setTitle:@"获取验证码" forState:UIControlStateNormal];
        if (_timer) {
            [_timer invalidate];
            _timer = nil;
        }
//        self.endBlock();
    } else {
        NSString *title = [NSString stringWithFormat:@"%ds",_timeIndex];
        [self setTitle:title forState:UIControlStateNormal];
    }
}

- (void)didMoveToWindow {
    [super didMoveToWindow];
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

@end
